import time

from django.views.generic import ListView, CreateView, DetailView , TemplateView, FormView
from .models import Post, Comment
from .forms import CommentForm
from calendar import month_name
from django.core.urlresolvers import reverse_lazy
from django.core.urlresolvers import reverse


class PostView(DetailView, ListView, CreateView):
    """Show post, associated comments and an 'add comment' form."""
    model = Post
    list_model = Comment
    modelform_class = CommentForm
    fk_attr = "post"
    template_name = 'blog/blog_base.html'
    
    
class PostDetailView(FormView):
    form_class = CommentForm
    template_name = 'blog/detailPost.html'
    
    def get_context_data(self, **kwargs):
        context = super(PostDetailView, self).get_context_data(**kwargs)
        context['id'] = self.kwargs.get('id')
        context['Post'] = Post.objects.get(id=self.kwargs.get('id'))
        context['Comments'] = Comment.objects.filter(post=self.kwargs.get('id'))
        return context
    
    def form_valid(self, form):
        PostUp= Post()
        try:
            PostUp= Post.objects.get(id=self.kwargs.get('id'))
        except:
            error ='El post ha sido borrado o no se encuentra actualmente'
        comment1 = Comment()
        comment1.text = form.cleaned_data['text']
        comment1.author = self.request.user
        comment1.post = PostUp
        comment1.save()
        PostUp.comments_count = PostUp.comments_count + 1
        PostUp.save()
        return super(PostDetailView , self).form_valid(form)
    
    def get_success_url(self):
        # Redirect to previous url
        return self.request.META.get('HTTP_REFERER', None)
 
    
    
class PostMainView(ListView):
    """Main listing """
    context_object_name = 'posts'
    model = Post
    paginate_by = 10
    template_name = "blog/blog_base.html"
    
    def months(self):
        """Make a list of months to show archive links."""
        if not Post.objects.count(): return list()

        # set up variables
        current_year, current_month = time.localtime()[:2]
        first       = Post.objects.order_by("created")[0]
        first_year  = first.created.year
        first_month = first.created.month
        months      = list()

        #
        
        # loop over years and months
        for year in range(current_year, first_year-1, -1):
            start, end = 12, 0
            if year == current_year : start = current_month
            if year == first_year   : end = first_month - 1

            for month in range(start, end, -1):
                if Post.objects.filter(created__year=year, created__month=month):
                    months.append((year, month, month_name[month]))
        return months


class ArchiveMonth(PostMainView):
    paginate_by = None

    def get_list_queryset(self):
        year, month = self.args
        return Post.objects.filter(created__year=year, created__month=month).order_by("created")
    